package com.firefighting.controller;

import java.io.IOException;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.codehaus.jackson.JsonGenerationException;
import org.codehaus.jackson.map.JsonMappingException;
import org.codehaus.jackson.map.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSONObject;
import com.firefighting.entity.Building;
import com.firefighting.entity.Contract;
import com.firefighting.service.BuildingService;
import com.firefighting.service.ContractService;
import com.firefighting.service.EnclosureService;
import com.firefighting.service.LocationService;
import com.firefighting.service.MaintenancePlanService;
import com.firefighting.service.TaskService;

@Controller
@RequestMapping("building")
public class BuildingController {

	@Autowired
	private BuildingService buildingService;
	@Autowired
	private EnclosureService enclosureService;
	@Autowired
	private ContractService contractService;
	@Autowired
	private TaskService taskService;
	@Autowired
	private LocationService locationService;
	@Autowired
	MaintenancePlanService maintenancePlanService;
	
	/**
	 * @function 根据合同id查询building内容,若id是-1返回添加建筑物页面
	 * @author Liuxc
	 * 
	 * @return
	 * 
	 * 
	 */
	@RequestMapping("getBuildingInfo")
	private String getBuildingInfo(HttpServletRequest request, Model model)
	{
		int id = Integer.parseInt(request.getParameter("id"));
		
		
		if(id == -1){//返回添加建筑物页面
			
			return "contract/addBuilding";
		}
		else//返回编辑建筑物页面
		{
			Building building = buildingService.selectBuildingById(id);
			model.addAttribute("content", building);
			return "contract/editBuilding";
		}
	
	}
	/**
	 * @author Liuxc
	 * @throws IOException 
	 * @throws JsonMappingException 
	 * @throws JsonGenerationException 
	 * @function 查询合同所有建筑物和总建筑面积
	 * */
	@RequestMapping("getAllBuilding")
	public String getAllBuilding(HttpServletRequest request,Model model) throws JsonGenerationException, JsonMappingException, IOException{
		//System.out.println("getAllBuilding");
		Integer buildingArea = -1;
		List<HashMap<String, Object>> buildingList = new ArrayList<HashMap<String,Object>>();
		Integer contractId = Integer.parseInt(request.getParameter("id"));
		//System.out.println(contractId);
		buildingList = buildingService.selectBuildingList(contractId);
		ObjectMapper objectMapper = new ObjectMapper();
		Contract contract = contractService.queryContract(contractId);
		String contractName = contract.getProjectName();
		buildingArea = contract.getBuildingArea();
		model.addAttribute("buildingList", objectMapper.writeValueAsString(buildingList));
		model.addAttribute("contractName", contractName);
		model.addAttribute("buildingArea", buildingArea);
		model.addAttribute("contractId", contractId);
		HttpSession session = request.getSession();
		session.setAttribute("currentContractId", contractId); 
		if(maintenancePlanService.IsContractHasTask(contractId)){//如果已经下发计划
			return "contract/NoAdd";
		}
		return "contract/buildService";
	}
	/**
	 * @author Hanjd
	 * @throws IOException 
	 * @throws JsonMappingException 
	 * @throws JsonGenerationException 
	 * @function 编辑总建筑面积
	 * */
	@RequestMapping("editBuildingArea")
	@ResponseBody
	public String editBuildingArea(HttpServletRequest request,Model model) throws JsonGenerationException, JsonMappingException, IOException{
		
		Integer contractId = Integer.parseInt(request.getParameter("id"));
		Integer buildingArea = Integer.parseInt(request.getParameter("buildingArea"));
		Contract contract = contractService.queryContract(contractId);
		contract.setBuildingArea(buildingArea);
		contractService.updateContract(contract);
		
		Map<String,Object> map = new HashMap<String,Object>();
		map.put("flag", true);
		return JSONObject.toJSONString(map);
	}
	
	/**
	 * @author Liuxc
	 * @function 根据id返回建筑物
	 * */
	@RequestMapping("selectBuildingById")
	public String selectBuildingById(HttpServletRequest request,Model model){
		Integer buildingId = Integer.parseInt(request.getParameter("buildingId"));
		String contractId = request.getParameter("contractId");
		//System.out.println("id"+contractId);
		model.addAttribute("contractId", contractId);
		if(buildingId == -1){
			return "contract/addBuilding";
		}else{
			Building building = buildingService.selectBuildingById(buildingId);
			model.addAttribute("building", building);
			return "contract/editBuilding";
		}
		
	}
	
	/**
	 * @author Liuxc
	 * @function 增加或者编辑建筑物
	 * */
	@RequestMapping("editBuilding")
	public String editeBuiding(HttpServletRequest request,HttpServletResponse response,Model model){
		Building building = new Building();
		String contractId=request.getParameter("id");
		model.addAttribute("contractId", contractId);
		JSONObject result=new JSONObject();
		if(maintenancePlanService.IsContractHasTask(Integer.parseInt(contractId))){//如果已经下发计划。不能增加建筑物
			result.put("success", false);
		}else{
			
			String buildingId = request.getParameter("buildingId");
			System.out.println("buildingid  "+buildingId);
			String buildingName = request.getParameter("buildingName");
			String buildingArea = request.getParameter("buildingArea");
			String undergroundArea = request.getParameter("undergroundArea");
			String overgroundArea = request.getParameter("overgroundArea");
			String overgroundLayer = request.getParameter("overgroundLayer");
			String undergroundLayer = request.getParameter("undergroundLayer");
			String buildingHeight = request.getParameter("buildingHeight");
			String enclosureLength = request.getParameter("enclosureLength");
			String lonlat = request.getParameter("latitude");
			String en = request.getParameter("");
			building.setContractId(Integer.parseInt(contractId));//需修改
			building.setBuildingName(buildingName);
			building.setBuildingArea(Integer.parseInt(buildingArea));
			building.setUndergroundLayer(Integer.parseInt(undergroundLayer));
			building.setUpgroundArea(Integer.parseInt(undergroundArea));
			building.setOvergroundArea(Integer.parseInt(overgroundArea));
			building.setOvergroundLayer(Integer.parseInt(overgroundLayer));
			building.setBuildingHeight(Integer.parseInt(buildingHeight));
			building.setEnclosureLength(Integer.parseInt(enclosureLength));
			String[] lonlat_arr;
			String sLongitude = "";
			String sLatitude = "";
			if(lonlat.contains(",")&&lonlat.indexOf(",")!=0&&lonlat.indexOf(",")!=(lonlat.length()-1)){
				lonlat_arr= lonlat.split(",");
				sLongitude = lonlat_arr[0];//经度
				sLatitude = lonlat_arr[1];//纬度
			}
			sLongitude = sLongitude.equals("")?"0.0":sLongitude;
			sLatitude = sLatitude.equals("")?"0.0":sLatitude;
			BigDecimal longitude = new BigDecimal(sLongitude);
			BigDecimal latitude = new BigDecimal(sLatitude);
			building.setLatitude(latitude);
			building.setLongitude(longitude);
			
			try {
				if (Integer.parseInt(buildingId) != -1) {  //更新操作
					building.setId(Integer.parseInt(buildingId));
					buildingService.updateBuilding(building);
					
				}else{//添加操作
					buildingService.addBuilding(building);
					
				}
			}catch (Exception e) {
				e.printStackTrace();
				result.put("success", true);
			}
		}

		return "redirect:/building/getAllBuilding.htm?id="+contractId;
	}
	/**
	 * @author Liuxc
	 * @function 删除建筑物
	 * 
	 * */
	@RequestMapping("deleteBuilding")
	@ResponseBody
	public String deleteBuilding(HttpServletRequest request,Model model){
		Map<String,Object> map = new HashMap<String,Object>();
		String buildingId = request.getParameter("id");
		String contractId = request.getParameter("contractId");
		if(maintenancePlanService.IsContractHasTask(Integer.parseInt(contractId))){//如果已经下发计划。不能删除建筑物
			map.put("hasPlan", true);
		}else{
			buildingService.deleteById(Integer.parseInt(buildingId));

			map.put("flag", true);
			
		}
		
		return JSONObject.toJSONString(map);
		
		//Integer contractId = Integer.parseInt(request.getParameter("contractId"));
/*		taskList = taskService.queryTaskBuildingId(Integer.parseInt(buildingId));
		for( int i = 0 ; i < taskList.size() ; i++) {//内部不锁定，效率最高，但在多线程要考虑并发操作的问题。
			Task the_task = taskList.get(i);
			int id = the_task.getId();
			List<com.firefighting.entity.Location> locationList = new ArrayList<com.firefighting.entity.Location>();
			locationList =locationService.queryLocationId(id); 
			if (null == locationList || locationList.size() ==0 ) {
				
			}
			else {
				for( int j = 0 ; j < locationList.size() ; j++) {
					com.firefighting.entity.Location location = locationList.get(i);
					int another_id = location.getId();
					locationService.deleteLocation(another_id);
				}
			}
			
			taskService.deleteTask(id);
		}*/
		

		
/*		JSONObject result=new JSONObject();
		result.put("success", true);
		return "redirect:/building/getAllBuilding";*/
		//return "redirect:/building/getAllBuilding?id="+contractId; 
	}
	
}
